<template>
  <div class="flex h-full">
    <a-card class="mr-2 h-full" :body-style="{ height: '100%', padding: '0 8px' }">
      <a-tabs v-model:active-key="activeKey" centered @change="queryTabs">
        <a-tab-pane key="0">
          <template #tab>
            <div class="px-3 text-center">科室</div>
          </template>
        </a-tab-pane>
        <a-tab-pane key="1">
          <template #tab>
            <div class="px-4 text-center">医生</div>
          </template>
        </a-tab-pane>
      </a-tabs>
      <a-input-search v-model:value="searchValue" :placeholder="activeKey === '1' ? '医生/助记码' : '科室/助记码'" @search="queryTabs" />
      <BaseList :data-source="dataSource" :loading="loading">
        <template #renderItem="{ item }">
          <div class="py-2 px-3" :class="selectedItem?.value === item.value ? 'active' : ''" @click="onHandleSelect(item)">
            <div class="flex justify-between">
              <div class="text-base font-bold text-primary truncate w-16">{{ item.name === '' ? '无' : item.name }}</div>
            </div>
            <div class="flex pt-2">
              <div class="flex w-24 truncate">
                <div class="department-status w-[22px] h-[22px] wait-background">
                  <div class="department-character w-[16px] h-[16px]">候</div>
                </div>
                <span class="text-grey">{{ item.hz ? item.hz : 0 }}</span>
              </div>
              <div class="flex justify-center w-24">
                <div class="department-status w-[22px] h-[22px] treat-background">
                  <div class="department-character w-[16px] h-[16px]">完</div>
                </div>
                <span class="text-grey">{{ item.ywz ? item.ywz : 0 }}</span>
              </div>
              <div class="flex justify-end w-24">
                <div class="department-status w-[22px] h-[22px] intact-background">
                  <div class="department-character w-[16px] h-[16px]">待</div>
                </div>
                <span class="text-grey">{{ item.dhz ? item.dhz : 0 }}</span>
              </div>
            </div>
          </div>
        </template>
      </BaseList>
    </a-card>
    <div class="flex flex-col flex-1 overflow-hidden">
      <SearchContainer @search="queryList" @reset="() => formRef.resetFields()">
        <a-form ref="formRef" :model="registerState">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item name="pyjm">
                <a-input v-model:value="registerState.pyjm" placeholder="姓名/助记码/卡号/手机号/身份证号" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </SearchContainer>
      <a-card class="mt-2 w-full flex-1">
        <div class="mb-3">
          <a-button type="primary" @click="onHandleAdd">
            <template #icon><plusOutlined /></template>挂号
          </a-button>
        </div>
        <BaseTable :loading="loading" column-code="00001015" fill :data-source="tableData" :scroll="{ x: 2000 }">
          <template #bodyCell="{ column, record, index }">
            <template v-if="column.dataIndex === 'xh'">
              {{ index + 1 }}
            </template>
            <template v-if="column.dataIndex === 'ghzt'">
              <a-tag v-if="record.ghzt === 0" color="blue">候诊中</a-tag>
              <a-tag v-else-if="record.ghzt === 1" color="blue">就诊中</a-tag>
              <a-tag v-else-if="record.ghzt === 2" color="red">已退号</a-tag>
              <a-tag v-else-if="record.ghzt === 3" color="green">已完诊</a-tag>
              <a-tag v-else-if="record.ghzt === 4" color="blue">待回珍</a-tag>
            </template>
            <template v-if="column.dataIndex == 'action'">
              <!-- <a-button type="link" size="small" @click="onHandleEdit(record)"> 修改 </a-button> -->
              <a-divider type="vertical" />
              <ConfirmModal description="确定退号?" @confirm="onConfirm(record)">
                <a-button type="text" danger size="small" :disabled="record.ghzt !== 0" @click="onHandleDoRegister(record)"> 退号 </a-button>
              </ConfirmModal>
              <a-divider type="vertical" />
              <a-button type="text" size="small"> 标签 </a-button>
              <a-divider type="vertical" />
              <a-button type="link" size="small" @click="onPrint(record)"> 挂号单 </a-button>
            </template>
          </template>
        </BaseTable>
      </a-card>
    </div>
    <RegisterModal
      v-model:open="registerOpen"
      :is-reservation-state="isReservationState"
      :row-data="rowData"
      :title="modalTitle"
      :department="selectedItem.value"
      @success="onSuceess(1)"
    />
    <EditRegister v-model:open="editRegisterOpen" :row-data="rowData" @success="onSuceess(2)" />
    <Refund v-model:open="priceOpen" :register-price="categoryPrice" :bill-number="billNumber" :loading-state="loadingState" @success="onSuccessPrice" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'
import { post, get } from '@/utils/request'
import SearchContainer from '@/components/SearchContainer'
import BaseList from '@/components/BaseList'
import BaseTable from '@/components/BaseTable'
import ConfirmModal from '@/components/ConfirmModal'
import RegisterModal from '@/components/RegisterModal'
import { getSystemConfig } from '@/utils/systemConfig'
import EditRegister from '@/views/out-registration/statistics/register-query/components/EditModal.vue'
import Refund from '../../components/RefundModal.vue'
import useAppStore from '../../store'

const isPrint = ref('')
const userInfo = useAppStore()
const route = useRoute()
const rowData = ref(null)
const registerOpen = ref(false)
const priceOpen = ref(false)
const editRegisterOpen = ref(false)
const activeKey = ref('0')
const loading = ref(false)
const loadingState = ref(false)
const tableData = ref([])
const dataSource = ref([])
const formRef = ref(null)
const modalTitle = ref('挂号')
const registerState = ref({})
const categoryPrice = ref(0)
const billNumber = ref('')
const reservationNumber = ref('')
const serialList = ref([])
const refundType = ref()
const isReservationState = ref(false)
const selectedItem = ref({
  value: null
})
const searchValue = ref('')
const tableItem = ref({})
// const onHandleEdit = (row) => {
//   rowData.value = row
//   modalTitle.value = '修改数据'
//   editRegisterOpen.value = true
// }
const onHandleAdd = () => {
  rowData.value = {}
  isReservationState.value = false
  modalTitle.value = '挂号'
  registerOpen.value = true
}
const onHandleDoRegister = (item) => {
  tableItem.value = item
}
const onConfirm = async (row) => {
  const { code, msg, data } = await post('/outp/mzdj/doCancel', { jzbh: row.jzbh, yybh: row.yybh })
  if (code === 0 && data) {
    categoryPrice.value = data.sjdj
    billNumber.value = data.pjhm
    serialList.value = data.dtlsh
    reservationNumber.value = data.yylsh
    refundType.value = data.tflx
    priceOpen.value = true
  } else {
    if (code !== 0) return message.error(msg || '退号失败')
    message.success('退号成功')
    queryTabs()
  }
}
const onHandleSelect = (item) => {
  selectedItem.value = item
}
const queryList = async () => {
  loading.value = true
  const params = {
    stdate: dayjs().format('YYYY-MM-DD'),
    eddate: dayjs().format('YYYY-MM-DD'),
    ksdm: activeKey.value === '0' && selectedItem.value.value ? [selectedItem.value.value] : [],
    pyjm: registerState.value.pyjm,
    type: '0',
    brId: '',
    brSfz: ''
  }
  activeKey.value === '1' && selectedItem.value.value !== null && (params.ghys = selectedItem.value.value)
  const { code, data } = await post('/outp/mzdj/getOutpRecordInfoList', params)
  loading.value = false
  if (code !== 0) return
  tableData.value = data
  tableData.value.forEach((item) => {
    item.ghsj = item.ghsj.substring(11, 19)
  })
}

const queryTabs = async () => {
  loading.value = true
  dataSource.value = []
  const { code, data } = await post('/outp/mzdj/getOutpRecordCountList', {
    type: activeKey.value, //科室 0 医生 1
    pyjm: searchValue.value
  })
  if (code !== 0) return
  loading.value = false
  dataSource.value = data.map((item) => ({
    name: activeKey.value === '0' ? item.ksmc : item.empName,
    value: activeKey.value === '0' ? item.ksdm : item.ysbh,
    hz: item.hz,
    yjz: item.yjz,
    ywz: item.ywz,
    dhz: item.dhz
  }))
  dataSource.value.unshift({
    name: '全部',
    value: null,
    hz: dataSource.value.reduce((total, item) => total + Number(item.hz), 0),
    yjz: dataSource.value.reduce((total, item) => total + Number(item.yjz), 0),
    ywz: dataSource.value.reduce((total, item) => total + Number(item.ywz), 0),
    dhz: dataSource.value.reduce((total, item) => total + Number(item.dhz), 0)
  })
  selectedItem.value = dataSource.value.length ? dataSource.value[0] : {}
}
// 打印
const onPrint = async (row) => {
  if (getSystemConfig('OUTP_REGISTER_PRINT_INVOICE_AFTER_CHARGE') === '0') return
  const { code, msg, data } = await post(isPrint.value, { jzbh: row.jzbh, pjhm: row.pjhm })
  if (code !== 0) return message.error(msg)
  window.openExe?.rpt(data) //调用winform打印
}

const onSuccessPrice = async (params) => {
  loadingState.value = true
  const { code, msg } = await post('/outp/oupCharge/doOutPRefund', {
    yylsh: reservationNumber.value,
    ...params,
    tflx: refundType.value,
    lshs: serialList.value,
    type: '1'
  })
  loadingState.value = false
  if (code !== 0) return message.error(msg)
  priceOpen.value = false
  message.success('退号成功')
  queryList()
}
watch(selectedItem, () => {
  queryList()
})
const onSuceess = () => {
  registerOpen.value = false
  editRegisterOpen.value = false
  selectedItem.value.value = null
  queryTabs()
  queryList()
  // if (state === 1) {
  //   setTimeout(() => {
  //     window.open(`/api/v1/outp/outPrint/printRegisteredChargeCertificate`)
  //   }, 1500)
  // }
}
//获取患者信息
const getPatientInfo = async () => {
  const { code, data } = await get('/common/patient/getPatientInfo?br_id=' + route.query.id)
  if (code !== 0) return
  rowData.value = { ...data }
  registerOpen.value = true
}
onMounted(() => {
  queryTabs()
  if (route.query?.id) {
    getPatientInfo()
  } else if (route.query?.state) {
    isReservationState.value = true
    rowData.value = { ...userInfo.patientInfo }
    registerOpen.value = true
  }
  // 0：通用|1：上海黑马|2：茗视光
  isPrint.value = getSystemConfig('REGISTRATION_FORM_PRINT_MODE') === '2' ? '/outp/outPrint/getRegistrationPrint' : '/outp/outPrint/getRegistrationBillPrint'
})
</script>

<style lang="less" scoped>
:deep(.ant-tabs-tab) {
  .ant-tabs-content {
    height: 100%;
    .ant-tabs-tabpane {
      display: flex;
      flex-direction: column;
      height: 100%;
      .ant-spin-nested-loading,
      .ant-spin-container {
        height: 100%;
      }
      .ant-spin-container {
        position: relative;
        .ant-list-empty-text {
          position: absolute;
          top: calc(50% - 84px);
          left: calc(50% - 55px);
        }
      }
    }
  }
}

.department-status {
  @apply flex justify-center items-center status-font rounded font-semibold mr-1;
}
.department-character {
  @apply flex justify-center items-center  bg-white rounded-round;
}

.wait-background {
  color: #7089f6;
  background-color: #7089f6;
}
.treat-background {
  color: #838be2;
  background-color: #838be2;
}
.intact-background {
  color: #a07bfb;
  background-color: #a07bfb;
}
.status-font {
  font-size: 12px;
}
.rounded-round {
  border-radius: 50%;
}
</style>
